package com.governtalk.backend.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.governtalk.backend.dto.AiSolverRequest;
import com.governtalk.backend.dto.AiSolverResponse;
import com.governtalk.backend.service.AiSolverService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class AiSolverServiceImpl implements AiSolverService {

    @Value("${ai.coze.api-key:default-api-key}")
    private String apiKey;

    @Value("${ai.coze.bot-id:default-bot-id}")
    private String botId;

    private final ObjectMapper objectMapper = new ObjectMapper();

    // 存储每个用户的对话ID
    private final Map<Long, String> userConversationIds = new ConcurrentHashMap<>();

    @Override
    public AiSolverResponse solveQuestion(AiSolverRequest request) {
        return callCozeApi(request, null);
    }

    @Override
    public AiSolverResponse solveQuestionWithImage(AiSolverRequest request, String imageUrl) {
        return callCozeApi(request, imageUrl);
    }

    @Override
    public String getUserConversationId(Long userId) {
        return userConversationIds.get(userId);
    }

    @Override
    public void clearUserConversation(Long userId) {
        userConversationIds.remove(userId);
    }

    @Override
    public void solveQuestionStream(AiSolverRequest request, SseEmitter emitter) {
        try {
            System.out.println("=== Service层：开始AI解题（流式传输） ===");
            System.out.println("问题: " + request.getQuestion());
            System.out.println("用户ID: " + request.getUserId());
            System.out.println("问题类型: " + request.getQuestionType());
            System.out.println("API密钥长度: " + (apiKey != null ? apiKey.length() : "null"));
            System.out.println("Bot ID: " + botId);
            System.out.println("SSE Emitter状态: " + (emitter != null ? "已创建" : "null"));
            
            // 使用流式传输
            System.out.println("=== Service层：开始流式传输 ===");
            callCozeApiStream(request, null, emitter);
            System.out.println("=== Service层：流式传输完成 ===");
            
        } catch (Exception e) {
            System.err.println("=== Service层：AI解题异常 ===");
            System.err.println("异常类型: " + e.getClass().getName());
            System.err.println("异常消息: " + e.getMessage());
            System.err.println("异常堆栈: ");
            e.printStackTrace();
            try {
                emitter.send(SseEmitter.event()
                    .name("error")
                    .data("AI解析失败: " + e.getMessage()));
                System.out.println("=== Service层：错误信息已发送给前端 ===");
            } catch (IOException ioException) {
                System.err.println("发送错误信息失败: " + ioException.getMessage());
                ioException.printStackTrace();
            }
            emitter.completeWithError(e);
            System.out.println("=== Service层：SSE连接已关闭 ===");
        }
    }

    @Override
    public void solveQuestionWithImageStream(AiSolverRequest request, String imageUrl, SseEmitter emitter) {
        try {
            System.out.println("=== 开始流式AI图片解题 ===");
            System.out.println("问题: " + request.getQuestion());
            System.out.println("用户ID: " + request.getUserId());
            System.out.println("图片URL: " + imageUrl);
            
            // 调用Coze API获取流式响应
            callCozeApiStream(request, imageUrl, emitter);
            
        } catch (Exception e) {
            System.err.println("流式AI图片解题失败: " + e.getMessage());
            e.printStackTrace();
            try {
                emitter.send(SseEmitter.event()
                    .name("error")
                    .data("AI图片解析失败: " + e.getMessage()));
            } catch (IOException ioException) {
                System.err.println("发送错误信息失败: " + ioException.getMessage());
            }
            emitter.completeWithError(e);
        }
    }

    private AiSolverResponse callCozeApi(AiSolverRequest request, String imageUrl) {
        try {
            System.out.println("=== Coze API 调用开始 ===");
        System.out.println("AI解题请求: " + request.getQuestion());
        System.out.println("用户ID: " + request.getUserId());
            System.out.println("图片URL: " + (imageUrl != null ? imageUrl : "无"));
            
            // 构建Coze API请求
            Map<String, Object> cozeRequest = new HashMap<>();
            cozeRequest.put("bot_id", botId);
            cozeRequest.put("user_id", "123456789");
            cozeRequest.put("stream", false);
            
            // 构建消息
            List<Map<String, Object>> messages = new ArrayList<>();
            Map<String, Object> message = new HashMap<>();
            message.put("content", request.getQuestion());
            message.put("content_type", "text");
            message.put("role", "user");
            message.put("type", "question");
            messages.add(message);
            cozeRequest.put("additional_messages", messages);
            cozeRequest.put("parameters", new HashMap<>());
            
            // 如果有图片，添加图片信息
            if (imageUrl != null && !imageUrl.isEmpty()) {
                System.out.println("=== Coze API：添加图片信息 ===");
                System.out.println("原始图片URL: " + imageUrl);
                
                // 确保图片URL是完整的URL
                String fullImageUrl = imageUrl;
                if (!imageUrl.startsWith("http://") && !imageUrl.startsWith("https://")) {
                    // 如果是相对路径，添加基础URL
                    fullImageUrl = "http://localhost:8080" + (imageUrl.startsWith("/") ? "" : "/") + imageUrl;
                    System.out.println("转换为完整URL: " + fullImageUrl);
                }
                
                Map<String, Object> imageMessage = new HashMap<>();
                imageMessage.put("content", fullImageUrl);
                imageMessage.put("content_type", "image");
                imageMessage.put("role", "user");
                imageMessage.put("type", "question");
                messages.add(imageMessage);
                System.out.println("=== Coze API：图片消息已添加 ===");
            }
            
            // 打印请求数据
            String jsonRequest = objectMapper.writeValueAsString(cozeRequest);
            System.out.println("=== Coze API 请求数据 ===");
            System.out.println(jsonRequest);
            System.out.println("=== 发送请求到 Coze API ===");
            
            // 发送HTTP请求到Coze API
            String response = sendHttpRequest(cozeRequest);
            
            // 打印响应数据
            System.out.println("=== Coze API 响应数据 ===");
            System.out.println(response);
            System.out.println("=== Coze API 调用结束 ===");
            
            // 解析响应
            return parseCozeResponse(response, request.getUserId());
            
        } catch (Exception e) {
            System.err.println("=== Coze API 调用失败 ===");
            System.err.println("错误信息: " + e.getMessage());
            e.printStackTrace();
            System.err.println("=== Coze API 调用失败结束 ===");
            
            // 返回错误响应
            return AiSolverResponse.builder()
                    .success(false)
                    .error("AI服务暂时不可用，请稍后重试")
                    .build();
        }
    }
    
    private void callCozeApiStream(AiSolverRequest request, String imageUrl, SseEmitter emitter) {
        try {
            System.out.println("=== callCozeApiStream：开始调用 Coze 流式 API ===");
            System.out.println("请求参数 - 问题: " + request.getQuestion());
            System.out.println("请求参数 - 用户ID: " + request.getUserId());
            System.out.println("请求参数 - 问题类型: " + request.getQuestionType());
            System.out.println("请求参数 - 图片URL: " + imageUrl);
            System.out.println("API配置 - Bot ID: " + botId);
            System.out.println("API配置 - API密钥长度: " + (apiKey != null ? apiKey.length() : "null"));
            System.out.println("SSE Emitter状态: " + (emitter != null ? "已创建" : "null"));
            
            // 构建Coze API请求
            System.out.println("=== callCozeApiStream：构建请求数据 ===");
            Map<String, Object> cozeRequest = new HashMap<>();
            cozeRequest.put("bot_id", botId);
            cozeRequest.put("user_id", "123456789");
            cozeRequest.put("stream", true);
            
            // 构建消息 - 使用正确的Coze API格式
            List<Map<String, Object>> messages = new ArrayList<>();
            
            // 添加文本消息
            Map<String, Object> textMessage = new HashMap<>();
            textMessage.put("content", request.getQuestion());
            textMessage.put("content_type", "text");
            textMessage.put("role", "user");
            messages.add(textMessage);
            System.out.println("=== callCozeApiStream：添加文本消息 ===");
            
            // 如果有图片，添加图片消息
            if (imageUrl != null && !imageUrl.isEmpty()) {
                System.out.println("=== callCozeApiStream：添加图片信息 ===");
                System.out.println("原始图片URL: " + imageUrl);
                
                // 确保图片URL是完整的URL
                String fullImageUrl = imageUrl;
                if (!imageUrl.startsWith("http://") && !imageUrl.startsWith("https://")) {
                    // 如果是相对路径，添加基础URL
                    fullImageUrl = "http://localhost:8080" + (imageUrl.startsWith("/") ? "" : "/") + imageUrl;
                    System.out.println("转换为完整URL: " + fullImageUrl);
                }
                
                Map<String, Object> imageMessage = new HashMap<>();
                imageMessage.put("content", fullImageUrl);
                imageMessage.put("content_type", "image");
                imageMessage.put("role", "user");
                messages.add(imageMessage);
                System.out.println("=== callCozeApiStream：图片消息已添加 ===");
            }
            
            cozeRequest.put("additional_messages", messages);
            cozeRequest.put("parameters", new HashMap<>());
            
            // 打印请求数据
            String jsonRequest = objectMapper.writeValueAsString(cozeRequest);
            System.out.println("=== callCozeApiStream：Coze 流式 API 请求数据 ===");
            System.out.println("请求体长度: " + jsonRequest.length() + " 字符");
            System.out.println("请求体内容: " + jsonRequest);
            
            // 发送流式HTTP请求到Coze API
            System.out.println("=== callCozeApiStream：准备发送HTTP请求 ===");
            sendStreamHttpRequest(cozeRequest, emitter);
            System.out.println("=== callCozeApiStream：HTTP请求发送完成 ===");
            
        } catch (Exception e) {
            System.err.println("=== callCozeApiStream：调用Coze流式API异常 ===");
            System.err.println("异常类型: " + e.getClass().getName());
            System.err.println("异常消息: " + e.getMessage());
            System.err.println("异常堆栈: ");
            e.printStackTrace();
            try {
                emitter.send(SseEmitter.event()
                    .name("error")
                    .data("AI服务暂时不可用，请稍后重试"));
                System.out.println("=== callCozeApiStream：错误信息已发送给前端 ===");
            } catch (IOException ioException) {
                System.err.println("发送错误信息失败: " + ioException.getMessage());
                ioException.printStackTrace();
            }
            emitter.completeWithError(e);
            System.out.println("=== callCozeApiStream：SSE连接已关闭 ===");
        }
    }
    
    private void sendStreamHttpRequest(Map<String, Object> requestData, SseEmitter emitter) throws Exception {
        System.out.println("=== sendStreamHttpRequest：开始发送流式请求到 Coze API ===");
        
        URL url = new URL("https://api.coze.cn/v3/chat");
        System.out.println("=== sendStreamHttpRequest：创建URL连接 ===");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        
        System.out.println("=== sendStreamHttpRequest：设置请求参数 ===");
        System.out.println("请求URL: " + url.toString());
        System.out.println("Authorization: Bearer " + apiKey.substring(0, 20) + "...");
        
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Authorization", "Bearer " + apiKey);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "text/event-stream");
        connection.setDoOutput(true);
        
        // 发送请求数据
        String jsonRequest = objectMapper.writeValueAsString(requestData);
        System.out.println("=== sendStreamHttpRequest：请求体大小: " + jsonRequest.length() + " 字节 ===");
        System.out.println("=== sendStreamHttpRequest：请求体内容: " + jsonRequest + " ===");
        
        System.out.println("=== sendStreamHttpRequest：开始发送请求数据 ===");
        try (OutputStream outputStream = connection.getOutputStream()) {
            byte[] input = jsonRequest.getBytes("utf-8");
            outputStream.write(input, 0, input.length);
            System.out.println("=== sendStreamHttpRequest：请求数据发送完成 ===");
        } catch (Exception e) {
            System.err.println("=== sendStreamHttpRequest：发送请求数据失败 ===");
            System.err.println("异常: " + e.getMessage());
            throw e;
        }
        
        // 读取流式响应
        System.out.println("=== sendStreamHttpRequest：开始读取响应 ===");
        int responseCode = connection.getResponseCode();
        System.out.println("=== sendStreamHttpRequest：响应状态码: " + responseCode + " ===");
        
        if (responseCode == HttpURLConnection.HTTP_OK) {
            try (InputStream inputStream = connection.getInputStream();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"))) {
                
                String line;
                String conversationId = null;
                StringBuilder fullAnswer = new StringBuilder();
                
                while ((line = reader.readLine()) != null) {
                    System.out.println("=== 收到流式数据行 ===");
                    System.out.println("原始行内容: " + line);
                    System.out.println("行长度: " + line.length());
                    
                    if (line.startsWith("event:")) {
                        String eventType = line.substring(6).trim();
                        System.out.println("=== 处理事件 ===");
                        System.out.println("事件类型: " + eventType);
                        
                        // 读取下一行的data
                        if ((line = reader.readLine()) != null && line.startsWith("data:")) {
                            String data = line.substring(5).trim();
                            System.out.println("=== 处理事件数据 ===");
                            System.out.println("事件数据: " + data);
                            System.out.println("数据长度: " + data.length());
                            
                            if ("conversation.chat.created".equals(eventType)) {
                                System.out.println("=== 处理对话创建事件 ===");
                                // 解析对话ID
                                try {
                                    JsonNode dataNode = objectMapper.readTree(data);
                                    if (dataNode.has("conversation_id")) {
                                        conversationId = dataNode.get("conversation_id").asText();
                                        System.out.println("获取到对话ID: " + conversationId);
                                        
                                        // 保存对话ID
                                        if (requestData.get("user_id") != null) {
                                            userConversationIds.put(Long.parseLong(requestData.get("user_id").toString()), conversationId);
                                            System.out.println("对话ID已保存到用户映射");
                                        }
                                    }
                                } catch (Exception e) {
                                    System.err.println("解析对话创建事件失败: " + e.getMessage());
                                    e.printStackTrace();
                                }
                            } else if ("conversation.message.delta".equals(eventType)) {
                                System.out.println("=== 处理消息增量事件 ===");
                                // 解析流式消息内容
                                try {
                                    JsonNode dataNode = objectMapper.readTree(data);
                                    System.out.println("消息增量数据节点: " + dataNode.toString());
                                    
                                    if (dataNode.has("role") && "assistant".equals(dataNode.get("role").asText())) {
                                        String content = "";
                                        
                                        // 优先使用content字段，如果为空则使用reasoning_content字段
                                        if (dataNode.has("content") && !dataNode.get("content").asText().isEmpty()) {
                                            content = dataNode.get("content").asText();
                                            System.out.println("使用content字段: " + content);
                                        } else if (dataNode.has("reasoning_content")) {
                                            content = dataNode.get("reasoning_content").asText();
                                            System.out.println("使用reasoning_content字段: " + content);
                                        }
                                        
                                        if (!content.isEmpty()) {
                                            fullAnswer.append(content);
                                            System.out.println("=== 发送消息片段到前端 ===");
                                            System.out.println("消息片段: " + content);
                                            System.out.println("当前完整回答长度: " + fullAnswer.length());
                                            
                                            // 发送给前端 - 直接发送消息内容，不需要嵌套JSON
                                            emitter.send(SseEmitter.event()
                                                .name("message")
                                                .data(content));
                                            
                                            System.out.println("消息片段已发送到前端");
                                        } else {
                                            System.out.println("消息片段为空，跳过");
                                        }
                                    } else {
                                        System.out.println("不是助手消息，跳过");
                                    }
                                } catch (Exception e) {
                                    System.err.println("解析消息事件失败: " + e.getMessage());
                                    e.printStackTrace();
                                }
                            } else if ("conversation.message.completed".equals(eventType)) {
                                System.out.println("=== 处理消息完成事件 ===");
                                // 消息完成 - 发送完整的消息内容
                                try {
                                    JsonNode dataNode = objectMapper.readTree(data);
                                    System.out.println("消息完成数据节点: " + dataNode.toString());
                                    
                                    if (dataNode.has("content") && dataNode.has("role") && "assistant".equals(dataNode.get("role").asText())) {
                                        String completeContent = dataNode.get("content").asText();
                                        System.out.println("=== 发送完整消息内容 ===");
                                        System.out.println("完整消息内容: " + completeContent);
                                        
                                        // 发送完整的消息内容
                                        emitter.send(SseEmitter.event()
                                            .name("message")
                                            .data(completeContent));
                                        
                                        // 发送完成信号
                                        emitter.send(SseEmitter.event()
                                            .name("complete")
                                            .data("AI解析完成"));
                                        
                                        System.out.println("完整消息和完成信号已发送");
                                    }
                                } catch (Exception e) {
                                    System.err.println("解析完成消息失败: " + e.getMessage());
                                    e.printStackTrace();
                                }
                                emitter.complete();
                                System.out.println("SSE连接已完成");
                                break;
                            } else if ("conversation.chat.completed".equals(eventType)) {
                                System.out.println("=== 处理对话完成事件 ===");
                                // 对话完成 - 也尝试发送完整内容
                                try {
                                    JsonNode dataNode = objectMapper.readTree(data);
                                    System.out.println("对话完成数据节点: " + dataNode.toString());
                                    
                                    if (dataNode.has("content") && dataNode.has("role") && "assistant".equals(dataNode.get("role").asText())) {
                                        String completeContent = dataNode.get("content").asText();
                                        System.out.println("=== 发送对话完成时的完整内容 ===");
                                        System.out.println("对话完成时的完整内容: " + completeContent);
                                        
                                        // 发送完整的消息内容
                                        emitter.send(SseEmitter.event()
                                            .name("message")
                                            .data(completeContent));
                                    }
                                } catch (Exception e) {
                                    System.err.println("解析对话完成消息失败: " + e.getMessage());
                                    e.printStackTrace();
                                }
                                
                                emitter.send(SseEmitter.event()
                                    .name("complete")
                                    .data("AI解析完成"));
                                emitter.complete();
                                System.out.println("对话完成，SSE连接已关闭");
                                break;
                            } else if ("error".equals(eventType)) {
                                System.out.println("=== 处理错误事件 ===");
                                try {
                                    JsonNode errorNode = objectMapper.readTree(data);
                                    String errorMsg = errorNode.has("msg") ? errorNode.get("msg").asText() : "未知错误";
                                    int errorCode = errorNode.has("code") ? errorNode.get("code").asInt() : -1;
                                    System.out.println("Coze API错误: " + errorCode + " - " + errorMsg);
                                    
                                    // 发送错误信息给前端
                                    emitter.send(SseEmitter.event()
                                        .name("error")
                                        .data("AI解析失败: " + errorMsg));
                                    
                                    emitter.completeWithError(new RuntimeException("Coze API错误: " + errorCode + " - " + errorMsg));
                                    return;
                                } catch (Exception e) {
                                    System.err.println("解析错误事件失败: " + e.getMessage());
                                    emitter.send(SseEmitter.event()
                                        .name("error")
                                        .data("AI解析失败: 服务器内部错误"));
                                    emitter.completeWithError(e);
                                    return;
                                }
                            } else {
                                System.out.println("未处理的事件类型: " + eventType);
                            }
                        } else {
                            System.out.println("事件后没有数据行");
                        }
                    } else {
                        System.out.println("不是事件行，跳过");
                    }
                }
                
                System.out.println("=== Coze 流式 API 调用完成 ===");
                System.out.println("完整回答: " + fullAnswer.toString());
                
            }
        } else {
            // 读取错误响应
            try (InputStream errorStream = connection.getErrorStream();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream, "utf-8"))) {
                
                StringBuilder errorResponse = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    errorResponse.append(line);
                }
                System.out.println("错误响应: " + errorResponse.toString());
                
                // 尝试解析错误响应
                try {
                    JsonNode errorNode = objectMapper.readTree(errorResponse.toString());
                    String errorMsg = errorNode.has("msg") ? errorNode.get("msg").asText() : "未知错误";
                    int errorCode = errorNode.has("code") ? errorNode.get("code").asInt() : responseCode;
                    System.out.println("Coze API错误码: " + errorCode + ", 错误信息: " + errorMsg);
                    
                    // 发送错误信息给前端
                    emitter.send(SseEmitter.event()
                        .name("error")
                        .data("AI解析失败: " + errorMsg));
                    
                    emitter.completeWithError(new RuntimeException("Coze API错误: " + errorCode + " - " + errorMsg));
                } catch (Exception e) {
                    System.err.println("解析错误响应失败: " + e.getMessage());
                    emitter.send(SseEmitter.event()
                        .name("error")
                        .data("AI解析失败: 服务器内部错误"));
                    emitter.completeWithError(new RuntimeException("Coze API请求失败: " + responseCode + " - " + errorResponse.toString()));
                }
            }
        }
    }
    
    private String sendHttpRequest(Map<String, Object> requestData) throws Exception {
        URL url = new URL("https://api.coze.cn/v3/chat");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        
        System.out.println("=== HTTP 请求详情 ===");
        System.out.println("请求URL: " + url.toString());
        System.out.println("请求方法: POST");
        System.out.println("Authorization: Bearer " + apiKey.substring(0, 20) + "...");
        
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Authorization", "Bearer " + apiKey);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        
        // 发送请求数据
        String jsonRequest = objectMapper.writeValueAsString(requestData);
        System.out.println("请求体大小: " + jsonRequest.length() + " 字节");
        
        try (OutputStream outputStream = connection.getOutputStream()) {
            byte[] input = jsonRequest.getBytes("utf-8");
            outputStream.write(input, 0, input.length);
        }
        
        // 读取响应
        int responseCode = connection.getResponseCode();
        System.out.println("响应状态码: " + responseCode);
        
        if (responseCode == HttpURLConnection.HTTP_OK) {
            try (InputStream inputStream = connection.getInputStream();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"))) {
                
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                System.out.println("响应体大小: " + response.length() + " 字符");
                return response.toString();
            }
        } else {
            // 读取错误响应
            try (InputStream errorStream = connection.getErrorStream();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream, "utf-8"))) {
                
                StringBuilder errorResponse = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    errorResponse.append(line);
                }
                System.out.println("错误响应: " + errorResponse.toString());
                throw new RuntimeException("Coze API请求失败: " + responseCode + " - " + errorResponse.toString());
            }
        }
    }

    private AiSolverResponse parseCozeResponse(String rawResponse, Long userId) {
        try {
            System.out.println("=== 开始解析 Coze API 响应 ===");
            JsonNode rootNode = objectMapper.readTree(rawResponse);
            String answer = "未能获取到AI解答。";
            List<String> followUpQuestions = new ArrayList<>();
            String conversationId = null;
            String messageId = null;

            // 检查是否有错误
            if (rootNode.has("code") && rootNode.get("code").asInt() != 0) {
                String errorMsg = rootNode.has("msg") ? rootNode.get("msg").asText() : "未知错误";
                System.out.println("Coze API 返回错误: " + errorMsg);
                return AiSolverResponse.builder()
                        .success(false)
                        .error("Coze API错误: " + errorMsg)
                        .build();
            }

            // 解析对话ID
            if (rootNode.has("conversation_id")) {
                conversationId = rootNode.get("conversation_id").asText();
                System.out.println("解析到对话ID: " + conversationId);
                if (userId != null) {
                userConversationIds.put(userId, conversationId);
                    System.out.println("已保存用户 " + userId + " 的对话ID: " + conversationId);
                }
            }

            // 解析消息ID
            if (rootNode.has("id")) {
                messageId = rootNode.get("id").asText();
                System.out.println("解析到消息ID: " + messageId);
            }

            // 解析消息内容
            if (rootNode.has("messages") && rootNode.get("messages").isArray()) {
                System.out.println("开始解析消息内容，消息数量: " + rootNode.get("messages").size());
                for (JsonNode messageNode : rootNode.get("messages")) {
                    if (messageNode.has("role") && "assistant".equals(messageNode.get("role").asText())) {
                        System.out.println("找到助手消息");
                        
                        // 优先使用content字段，如果为空则使用reasoning_content字段
                        if (messageNode.has("content") && !messageNode.get("content").asText().isEmpty()) {
                            answer = messageNode.get("content").asText();
                        } else if (messageNode.has("reasoning_content")) {
                            answer = messageNode.get("reasoning_content").asText();
                        }
                        
                        if (!answer.isEmpty()) {
                            System.out.println("解析到AI回复内容: " + answer.substring(0, Math.min(100, answer.length())) + "...");
                        }
                        
                        // 提取相关问题建议
                        if (messageNode.has("additional_messages") && messageNode.get("additional_messages").isArray()) {
                            System.out.println("开始解析相关问题建议");
                            for (JsonNode additionalMsg : messageNode.get("additional_messages")) {
                                if (additionalMsg.has("type") && "suggested".equals(additionalMsg.get("type").asText())) {
                                    if (additionalMsg.has("content")) {
                                        followUpQuestions.add(additionalMsg.get("content").asText());
                                        System.out.println("添加相关问题: " + additionalMsg.get("content").asText());
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // 如果没有找到答案，使用默认回复
            if (answer.equals("未能获取到AI解答。")) {
                answer = "🤖 您好！我是AI智能解题助手。我收到了您的问题，正在为您分析...\n\n" +
                        "很抱歉，我暂时无法提供准确的解答，请稍后重试或尝试重新描述您的问题。";
                System.out.println("使用默认回复");
            }

            System.out.println("=== 解析完成，最终结果 ===");
            System.out.println("AI回复: " + answer.substring(0, Math.min(200, answer.length())) + "...");
            System.out.println("相关问题数量: " + followUpQuestions.size());
            System.out.println("对话ID: " + conversationId);
            System.out.println("消息ID: " + messageId);
            System.out.println("=== Coze API 响应解析结束 ===");

            return AiSolverResponse.builder()
                    .answer(answer)
                    .followUpQuestions(followUpQuestions)
                    .conversationId(conversationId)
                    .messageId(messageId)
                    .success(true)
                    .build();
        } catch (Exception e) {
            System.err.println("解析Coze API响应失败: " + e.getMessage());
            e.printStackTrace();
            return AiSolverResponse.builder()
                    .success(false)
                    .error("解析AI响应失败: " + e.getMessage())
                    .build();
        }
    }
}
